import 'package:flutter/material.dart';
import '../model/baby.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';

class EditBabyDialog extends StatefulWidget {
  final Baby? baby;

  const EditBabyDialog({Key? key, this.baby}) : super(key: key);

  @override
  _EditBabyDialogState createState() => _EditBabyDialogState();
}

class _EditBabyDialogState extends State<EditBabyDialog> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  String _gender = 'M';
  DateTime _birthDate = DateTime.now();
  String? _avatarPath;

  @override
  void initState() {
    super.initState();
    if (widget.baby != null) {
      _nameController.text = widget.baby!.name;
      _gender = widget.baby!.gender;
      _birthDate = widget.baby!.birthDate;
      _avatarPath = widget.baby!.avatarUrl;
    }
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text(widget.baby == null ? '添加宝宝' : '编辑宝宝'),
      content: SingleChildScrollView(
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              _buildAvatarPicker(),
              SizedBox(height: 16),
              TextFormField(
                controller: _nameController,
                decoration: InputDecoration(
                  labelText: '宝宝名字',
                  border: OutlineInputBorder(),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入宝宝名字';
                  }
                  return null;
                },
              ),
              SizedBox(height: 16),
              Row(
                children: [
                  Expanded(
                    child: SegmentedButton<String>(
                      segments: [
                        ButtonSegment(value: 'M', label: Text('男宝')),
                        ButtonSegment(value: 'F', label: Text('女宝')),
                      ],
                      selected: {_gender},
                      onSelectionChanged: (Set<String> selection) {
                        setState(() => _gender = selection.first);
                      },
                    ),
                  ),
                ],
              ),
              SizedBox(height: 16),
              ListTile(
                title: Text('出生日期'),
                subtitle: Text(
                  '${_birthDate.year}年${_birthDate.month}月${_birthDate.day}日',
                ),
                trailing: Icon(Icons.calendar_today),
                onTap: _selectBirthDate,
              ),
            ],
          ),
        ),
      ),
      actions: [
        TextButton(child: Text('取消'), onPressed: () => Navigator.pop(context)),
        ElevatedButton(child: Text('保存'), onPressed: _saveBaby),
      ],
    );
  }

  Widget _buildAvatarPicker() {
    return GestureDetector(
      onTap: _pickImage,
      child: CircleAvatar(
        radius: 40,
        backgroundImage:
            _avatarPath != null ? FileImage(File(_avatarPath!)) : null,
        child: _avatarPath == null ? Icon(Icons.add_a_photo, size: 40) : null,
      ),
    );
  }

  Future<void> _pickImage() async {
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(source: ImageSource.gallery);

    if (image != null) {
      setState(() => _avatarPath = image.path);
    }
  }

  Future<void> _selectBirthDate() async {
    final picked = await showDatePicker(
      context: context,
      initialDate: _birthDate,
      firstDate: DateTime(2000),
      lastDate: DateTime.now(),
    );

    if (picked != null) {
      setState(() => _birthDate = picked);
    }
  }

  void _saveBaby() {
    if (_formKey.currentState!.validate()) {
      final baby = Baby(
        id: widget.baby?.id ?? DateTime.now().toString(),
        name: _nameController.text,
        gender: _gender,
        birthDate: _birthDate,
        avatarUrl: _avatarPath,
        isDefault: widget.baby?.isDefault ?? false,
      );

      Navigator.pop(context, baby);
    }
  }
}
